#!/usr/bin/python
'''
The mail module of the LifeParser Project.

Author          :                Naresh Pratap Singh
E-Mail          :                MAIL2NARESH@GMAIL.COM
Date            :                Jan 17 2011
Project Advisor :                Prof. Steven Skiena
'''

import siteConfig
import xoauth
import eMailService, eMailFetch, eMailParser
import errorStrings, debugTrace
import repositoryIface
import email, email.header
import os, sys, traceback
import eMailProcessor
import enronConfig
import mailDirReader

#These values are provided by the service provider when registering the application.
enronRepoRoot			= enronConfig.enronRepo
enronRepoType			= 'FILE'

errorStringsInst    = errorStrings.errorStrings()
debugTraceInst      = debugTrace.debugTrace(siteConfig.debugEnabled)

def downloadMails(userName):
	enronRepoInst	= repositoryIface.repositoryIface(enronRepoType, enronRepoRoot, siteConfig.debugEnabled)
	enronRepoInst.doConnectToDataStore()
	enronRepoInst.doSelectDataStore(userName)
	enronParserInst = eMailParser.eMailParser()
	
	readerInst		= mailDirReader.mailDirReader(enronConfig.enronMailDir)
	mailBoxList		= readerInst.listMailbox(userName)

	for mailBox in mailBoxList:
		result			= readerInst.fetchMails(userName, [mailBox])
		'''
		Write the fetched data to repository.
		Currently, each mail header is stored in a separate file.
		Only headers are being fetched and stored.
		'''
		totalMails		= len(result)
		remMails		= totalMails

		for mailEntry in result:
			mailHeader      = email.message_from_string(str(mailEntry))
			messageId       = email.header.decode_header(mailHeader[ 'Message-ID' ])[ 0 ][ 0 ]
			cleanMessageId  = enronParserInst.doCleanupForFilename(messageId)
			if mailBox.lower().find('sent') != -1 or mailBox.lower().find('send') != -1:
				entryName       = 'sent' + userName + cleanMessageId + siteConfig.fileSuffix
			else:
				entryName       = 'recv' + userName + cleanMessageId + siteConfig.fileSuffix
				
			#Transform the message into a storage format.
			enronRepoInst.doUpdateItem(entryName, str(mailEntry))
			remMails		= remMails - 1
    
def handleWebRequest(user, listFile = None):
	mailProcessorInst	= eMailProcessor.eMailProcessor(enronRepoRoot, enronRepoType, siteConfig.debugEnabled)
	if user is not None:
		try:
			#downloadMails(user)
			mailProcessorInst.processEMails(user)
			if listFile is not None:
				listFile.write(user + '\n')
		except:
			debugTraceInst.doPrintTrace(errorStringsInst.getFailedRequestError(), sys.exc_info()[2])
        
if __name__ == '__main__':
    
    '''
        Check if the request is triggered from the Web.
        If so, hand it over to appropriate handler.
    '''
    if len(sys.argv) >1:
        handleWebRequest(sys.argv[1])
    else:
		userListFileName	= os.path.join(siteConfig.analysisDir, enronConfig.enronProcessedUserFile)
		processedUsers		= None
		listFile			= open(userListFileName, 'a+')
		if os.path.getsize(userListFileName) != 0:
			processedUsers	= listFile.readlines()
		
		reader		= mailDirReader.mailDirReader(enronConfig.enronMailDir)
		userList	= reader.getUsers()
		
		for user in userList:
			if processedUsers is not None:
				try:
					processedUsers.index(user+'\n')
					continue
				except:
					pass
			print "Fetching Mails for User: " + user		
			handleWebRequest(user, listFile)
			listFile.flush()
		
		listFile.close()
